﻿

using CrayonAPI.Core.Entity.LogDB;
using CrayonAPI.Core.SqlSugar;
using SqlSugar;
using System.Reflection;

namespace CrayonAPI.Core;
public static class SqlSugarSetup
{
    public static ITenant ITenant { get; set; }
    public static void AddSqlsugar(this IServiceCollection services)
    {
        var configConnection = App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs");

        SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
        db =>
        {
            // 单例参数配置，所有上下文生效
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql);//输出sql
            };
        });

        ITenant = sqlSugar;

        services.AddSingleton<ISqlSugarClient>(sqlSugar);
        services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册

        configConnection.ForEach(config =>
        {
            if (config.ConfigId == SqlSugarConst.LogConfigId)
            {
                SqlSugarScopeProvider dbProvider = sqlSugar.GetConnectionScope(config.ConfigId);
                dbProvider.DbMaintenance.CreateDatabase();
                dbProvider.CodeFirst.InitTables<LogInfo>();
            }
        });

    }
}